import { FC, FormEvent } from 'react';
import Box from '@mui/joy/Box';
import { useError, useVM } from '@todo/ui';

import Stack from '@mui/joy/Stack';
import Button from '@mui/joy/Button';
import { useRouter } from 'react-router5';
import Typography from '@mui/joy/Typography';
import Input from '@mui/joy/Input';
import ThemeSwitcher from '../../core/view/Header/components/ThemeSwitcher.tsx';
import LanguageSwitcher from '../../core/view/Header/components/LanguageSwitcher.tsx';
import { useTranslation } from 'react-i18next';
import ReportGmailerrorredRoundedIcon from '@mui/icons-material/ReportGmailerrorredRounded';
import { InfoOutlined } from '@mui/icons-material';
import { AuthService } from '../service/auth.service.ts';
import GlobalStyles from '@mui/joy/GlobalStyles';
import Alert from '@mui/joy/Alert';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import FormHelperText from '@mui/joy/FormHelperText';
import Checkbox from '@mui/joy/Checkbox';
import Link from '@mui/joy/Link';

interface FormElements extends HTMLFormControlsCollection {
  email: HTMLInputElement;
  password: HTMLInputElement;
  persistent: HTMLInputElement;
}
interface SignInFormElement extends HTMLFormElement {
  readonly elements: FormElements;
}

const LoginPage: FC = () => {
  const vm = useVM(AuthService);
  const router = useRouter();
  const { t } = useTranslation('auth');
  const { formError, errorMessage, setError } = useError();

  const loginHandler = async (event: FormEvent<SignInFormElement>) => {
    event.preventDefault();
    const { email, password, persistent } = event.currentTarget.elements;
    const { err } = await vm.login(
      email.value,
      password.value,
      persistent.checked,
    );
    if (!err) {
      router.navigate('home');
      return;
    }
    setError(err);
  };

  return (
    <>
      <GlobalStyles
        styles={{
          ':root': {
            '--Form-maxWidth': '800px',
            '--Transition-duration': '0.4s', // set to `none` to disable transition
          },
        }}
      />
      <Box
        sx={(theme) => ({
          width: { xs: '100%', md: '50vw' },
          transition: 'width var(--Transition-duration)',
          transitionDelay: 'calc(var(--Transition-duration) + 0.1s)',
          position: 'relative',
          zIndex: 1,
          display: 'flex',
          justifyContent: 'flex-end',
          backdropFilter: 'blur(12px)',
          backgroundColor: 'rgba(255 255 255 / 0.2)',
          [theme.getColorSchemeSelector('dark')]: {
            backgroundColor: 'rgba(19 19 24 / 0.4)',
          },
        })}
      >
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            minHeight: '100dvh',
            width: '100%',
            px: 2,
          }}
        >
          <Box
            component="main"
            sx={{
              my: 'auto',
              py: 2,
              pb: 5,
              display: 'flex',
              flexDirection: 'column',
              gap: 2,
              width: 400,
              maxWidth: '100%',
              mx: 'auto',
              borderRadius: 'sm',
              '& form': {
                display: 'flex',
                flexDirection: 'column',
                gap: 2,
              },
              [`& .MuiFormLabel-asterisk`]: {
                visibility: 'hidden',
              },
            }}
          >
            {errorMessage && (
              <Alert
                color="danger"
                size="md"
                variant="soft"
                startDecorator={<ReportGmailerrorredRoundedIcon />}
              >
                {errorMessage}
              </Alert>
            )}
            <Stack gap={4} sx={{ mt: 2 }}>
              <form onSubmit={loginHandler}>
                <FormControl required error={Boolean(formError.email)}>
                  <FormLabel>{t('email')}</FormLabel>
                  <Input
                    type="email"
                    name="email"
                    autoComplete="on"
                    value="admin@mail.com"
                  />
                  {formError.email && (
                    <FormHelperText>
                      <InfoOutlined /> {formError.email}
                    </FormHelperText>
                  )}
                </FormControl>
                <FormControl required error={Boolean(formError.password)}>
                  <FormLabel>{t('password')}</FormLabel>
                  <Input
                    type="password"
                    name="password"
                    autoComplete="current-password"
                    value="aaAA@123"
                  />
                  {formError.password && (
                    <FormHelperText>
                      <InfoOutlined /> {formError.password}
                    </FormHelperText>
                  )}
                </FormControl>
                <Stack gap={4} sx={{ mt: 2 }}>
                  <Box
                    sx={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}
                  >
                    <Checkbox
                      size="sm"
                      label={t('rememberMe')}
                      name="persistent"
                    />
                    <Link level="title-sm" href="#replace-with-a-link">
                      {t('forgotPassword')}
                    </Link>
                  </Box>
                  <Button type="submit" fullWidth>
                    {t('signIn')}
                  </Button>
                  <Stack direction="row" justifyContent="center">
                    <ThemeSwitcher />
                    <LanguageSwitcher />
                  </Stack>
                </Stack>
              </form>
            </Stack>
          </Box>
          <Box component="footer" sx={{ py: 3 }}>
            <Typography level="body-xs" textAlign="center">
              © Code interview admin panel {new Date().getFullYear()}
            </Typography>
          </Box>
        </Box>
      </Box>
      <Box
        sx={(theme) => ({
          height: '100%',
          position: 'fixed',
          right: 0,
          top: 0,
          bottom: 0,
          left: { xs: 0, md: '50vw' },
          transition:
            'background-image var(--Transition-duration), left var(--Transition-duration) !important',
          transitionDelay: 'calc(var(--Transition-duration) + 0.1s)',
          backgroundColor: 'background.level1',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat',
          backgroundImage:
            'url(https://images.unsplash.com/photo-1527181152855-fc03fc7949c8?auto=format&w=1000&dpr=2)',
          [theme.getColorSchemeSelector('dark')]: {
            backgroundImage:
              'url(https://images.unsplash.com/photo-1572072393749-3ca9c8ea0831?auto=format&w=1000&dpr=2)',
          },
        })}
      />
    </>
  );
};

export default LoginPage;
